package com.example.quartzdemo.controller;

import com.example.quartzdemo.Entity.QuartzBean;
import com.example.quartzdemo.memory.CacheFactory;
import com.example.quartzdemo.memory.LocalCache;
import com.example.quartzdemo.memory.LocalCacheTypeEnum;
import com.example.quartzdemo.utils.QuartzUtils;
import io.swagger.annotations.ApiOperation;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author yeyangtao
 * @since 2022/6/16 15:30
 */
@RestController
@RequestMapping("/quartz")
public class JobController {

    //注入任务调度
    @Autowired
    private Scheduler scheduler;

    private static LocalCache localCache = CacheFactory.getLocalCache(LocalCacheTypeEnum.LIST);


    @ApiOperation(value = "查询任务")
    @PostMapping("/listJob")
    @ResponseBody
    public Object listJob() {
        return localCache.getAll();
    }

    @ApiOperation(value = "创建任务")
    @PostMapping("/createJob")
    @ResponseBody
    public String createJob(@RequestBody QuartzBean quartzBean) {
        try {
            //进行测试所以写死
            quartzBean.setJobClass("com.example.quartzdemo.service." + quartzBean.getJobClass());
            quartzBean.setCronExpression("*/10 * * * * ?");
            // */10 * * * * ?
            quartzBean.setId(UUID.randomUUID().toString());
            if (QuartzUtils.createScheduleJob(scheduler, quartzBean)) {
                quartzBean.setStatus(1);
                localCache.add(quartzBean);
            }

        } catch (Exception e) {
            return "创建失败";
        }
        return "创建成功";
    }

    @PutMapping("/pauseJob")
    @ResponseBody
    public String pauseJob(@RequestParam String id) {
        try {
            QuartzUtils.pauseScheduleJob(scheduler, id);
        } catch (Exception e) {
            return "暂停失败";
        }
        return "暂停成功";
    }

    @PostMapping("/runOnce")
    @ResponseBody
    public String runOnce(@RequestParam String id) {
        try {
            QuartzUtils.runOnce(scheduler, id);
        } catch (Exception e) {
            return "运行一次失败";
        }
        return "运行一次成功";
    }

    @PostMapping("/resume")
    @ResponseBody
    public String resume(@RequestParam String id) {
        try {

            QuartzUtils.resumeScheduleJob(scheduler, id);
        } catch (Exception e) {
            return "启动失败";
        }
        return "启动成功";
    }

    @PutMapping("/update")
    @ResponseBody
    public String update(QuartzBean quartzBean) {
        try {
            //进行测试所以写死
            quartzBean.setJobClass("com.hjljy.blog.Quartz.MyTask1");
            quartzBean.setJobName("test1");
            quartzBean.setCronExpression("10 * * * * ?");
            QuartzUtils.updateScheduleJob(scheduler, quartzBean);
        } catch (Exception e) {
            return "启动失败";
        }
        return "启动成功";
    }
}
